package com.cdyGateway.gatewayFilter;

import entity.Result;
import entity.StatusCode;
import entity.authToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;

/**
 * @author ：cdy
 * @date ：Created in 2020/11/16 11:17
 * @description：www.cdyong.cn
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {


    //排除过滤的 uri 地址
    private static final String LOGIN_URI = "/user/login";
    private static final String REGISTER_URI = "/user/register";
    private static final String AUTH_TOKEN = "Authorization";

    @Autowired(required = false)
    private authToken authToken;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        if(authToken==null)  return chain.filter(exchange);

        RequestPath path=exchange.getRequest().getPath();
        String url=path.value();

        if(path.value().contains(LOGIN_URI)||path.value().contains(REGISTER_URI))   return chain.filter(exchange);

        /**
         * 从请求中获取是否有token参数
         */
        String token = exchange.getRequest().getHeaders().getFirst(AUTH_TOKEN);
        if(!authToken.checker(token)){
            //不存在，直接返回验证失败，让其重新登录
            ServerHttpResponse response = exchange.getResponse();
            Result result=  new Result(false, StatusCode.ACCESSERROR,"权限不足");

            byte[] bits = result.toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }


        ServerHttpRequest request= exchange.getRequest().mutate().headers(httpHeaders->{
           httpHeaders.add(AUTH_TOKEN,token);
        }).build();

        ServerWebExchange webExchange= exchange.mutate().request(request).build();

        /**
         * 通过这个过滤器，进入过滤链中的下一个过滤器
         */
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
